﻿using Extensions.Attributes;
using GraphQL;
using GraphQL.Types;
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace GraphQLDomain.Utils
{
    public static class GraphTypeHelper
    {
        /// <summary>
        /// 根据映射类型的DisplayName生成Description
        /// </summary>
        /// <typeparam name="TSourceType"></typeparam>
        /// <param name="graphType"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string GetDescription<TSourceType>(this GraphType graphType, string propertyName = null)
        {
            return typeof(TSourceType)
                .GetAttributeValue<DisplayNameAttribute, string>(x => x.DisplayName, propertyName);
        }

        //public static string GetDescription<TSourceType>(this GraphType graphType, string propertyName = null)
        //{
        //    return typeof(TSourceType)
        //        .GetAttributeValue<DisplayNameAttribute, string>(x => x.DisplayName, propertyName);
        //}

        /// <summary>
        /// 根据映射的属性添加字段
        /// </summary>
        /// <typeparam name="TSourceType"></typeparam>
        /// <param name="graphType"></param>
        public static void AddFields<TSourceType>(this ComplexGraphType<TSourceType> graphType)
        {
            var sourceType = typeof(TSourceType);
            if (sourceType != null)
            {
                var propertyInfos = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                    .Where(prop =>
                    !(prop.CanRead ? prop.GetMethod : prop.SetMethod).IsVirtual
                    && !prop.PropertyType.IsEnum);

                foreach (var property in propertyInfos)
                {
                    graphType.AddField(new FieldType
                    {
                        Name = property.Name,
                        Description = property.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName,
                        Type = property.PropertyType.GetGraphTypeFromType(property.PropertyType.IsNullable()),
                        DefaultValue = property.GetCustomAttribute<DefaultValueAttribute>()?.Value
                    });
                }
            }
        }
        /// <summary>
        /// 根据映射的属性添加字段
        /// </summary>
        /// <typeparam name="TSourceType"></typeparam>
        /// <param name="graphType"></param>
        public static void AddFields<TSourceType>(this EnumerationGraphType graphType)
        {
            foreach (var name in Enum.GetNames(typeof(TSourceType)))
            {
                graphType.AddValue(
                    name: name,
                    description: graphType.GetDescription<TSourceType>(name),
                    value: Enum.Parse(typeof(TSourceType), name));
            }
        }

    }
}
